import {ColumnEditRule} from 'vxe-table'
import {RulesItem, RulesOther, RulesItemCallbackPlus} from '../elementConfig/index'
import typeOfUtils from '@/utils/type-of-utils'
import {deepClone} from '@/utils'
import {ColumnEditValidErrParams} from 'vxe-table/types/validator'


export class MyVxeUtils {
  public static vxeTableRulesToElementRules<T>(rules: { [field: string]: RulesItem<T>[] }): { [field: string]: ColumnEditRule[] } {
    const result = {}
    Object.keys(rules).forEach(key => {
      const rule = rules[key]
      if (typeOfUtils.isNotArray(rule)) {
        alert(`表格校验规则${key}必须是一个数组`)
      } else {
        const clone = deepClone(rule) as RulesItem<T>[]
        const resultItem: any[] = []
        clone.forEach(r => {
          if (r.validator) {
            const validator = (params: ColumnEditValidErrParams): Promise<Error> => {
              return new Promise((resolve, reject) => {
                const other: RulesOther<T> = {
                  row: params.row as T,
                  rowIndex: params.rowIndex,
                  column: params.column,
                  columnIndex: params.columnIndex,
                  $table: params.$table
                }
                const callBack = (error?: Error) => {
                  return RulesItemCallbackPlus(resolve, reject, error)
                }
                // @ts-ignore
                r.validator(params.rule as RulesItem<T>, params.cellValue, callBack, other)
              })
            }
            resultItem.push({
              ...r,
              validator
            })
          } else {
            resultItem.push(r)
          }
        })
        result[key] = resultItem
      }
    })
    return result
  }
}
